package com.code2roc.fastboot.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSON;
import com.code2roc.fastboot.model.ZTreeNode;

public class ZTreeBuilder {
    public static List<ZTreeNode> BuildTree(List<ZTreeNode> treeNodeList){
        List<ZTreeNode> result = new ArrayList<ZTreeNode>();
        //获取顶级节点
        List<ZTreeNode> topNodeList = treeNodeList.stream().filter((ZTreeNode t)->t.getTopNode()).collect(Collectors.toList());
        topNodeList.sort(((h1, h2) -> h2.getSotNum().compareTo(h1.getSotNum())));
        for (ZTreeNode treeNode:topNodeList) {
            ZTreeNode copyNode = JSON.parseObject(JSON.toJSONString(treeNode),ZTreeNode.class);
            result.add(copyNode);
            BuildSubTree(treeNodeList,copyNode);
        }
        return result;
    }

    private static void BuildSubTree(List<ZTreeNode> treeNodeList,ZTreeNode parentNode){
        //查询父节点下是否有子节点
        List<ZTreeNode> childList = treeNodeList.stream().filter((ZTreeNode t)->t.getpId().equals(parentNode.getId())).collect(Collectors.toList());
        childList.sort(((h1, h2) -> h2.getSotNum().compareTo(h1.getSotNum())));
        if(childList.size()>0){
            //设置父节点有子节点
            parentNode.setParent(true);
            for (int i=0;i<childList.size();i++){
                ZTreeNode t = childList.get(i);
                //将子节点添加到父节点的children数组中
                ZTreeNode copyNode = JSON.parseObject(JSON.toJSONString(t),ZTreeNode.class);
                parentNode.addChildNode(copyNode);
                //对子节点进行递归
                BuildSubTree(treeNodeList,copyNode);
            }
        }else{
            parentNode.setParent(false);
        }
    }
}
